package com.act;

import java.util.Random;

import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * 状态栏的显示
 * 
 * @author Administrator
 *
 */
public class Notifier {

	private static final String TAG = LogUtil.getClassName(Notifier.class);
	
	private static final Random random =new Random(System.currentTimeMillis());
	
	private SharedPreferences sharePre = null;
	private NotificationManager notificationManager = null;
	
	private Context context =null;
	public Notifier(Context context)
	{
		this.context = context;
		
		sharePre = context.getSharedPreferences(Constants.SET_NOTIFICATION_NAME, Context.MODE_PRIVATE);
		notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	}
	
	public void notify(int notificationId,String apiKey,String title,String message,String url)
	{
		Log.d(TAG, "Notifier.. notify .. is running.");
		
		Notification notification = new Notification();
		
		notification.icon = getNotificationIcon();
		notification.defaults = Notification.DEFAULT_ALL;
		if(isNotificationSoundEnable())
		{
			notification.defaults |= Notification.DEFAULT_SOUND;
		}
		if(isNotificationVibratorEnable())
		{
			notification.defaults |= Notification.DEFAULT_VIBRATE;
		}
		Intent intent = new Intent();
		intent.setClass(context, DetailActivity.class);
		intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
		intent.putExtra(Constants.NOTIFICATION_TITLE, title);
		intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
		intent.putExtra(Constants.NOTIFICATION_URL, url);
		
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context, title, message, pendingIntent);
		
		notificationManager.notify(random.nextInt(), notification);
	}

	private int getNotificationIcon()
	{
		return sharePre.getInt(Constants.NOTIFICATION_ICON, 0);
	}
	private boolean isNotificationVibratorEnable() {
		
		return sharePre.getBoolean(Constants.SET_NOTIFICATION_SOUND, false);
	}

	private boolean isNotificationSoundEnable() {

		return sharePre.getBoolean(Constants.SET_NOTIFICATION_VIBRATOR, false);
	}
}
